<?php
namespace Cyfy\Modules\Users\Forms;

use \Cyfy\Message;
use \Cyfy\Modules\Forms;
use \Cyfy\Modules\Users\Current;
use \Cyfy\Modules\Users\Module;

/**
 * User account settings form.
 *
 * @author Dandelion <dandelion8888@gmail.com>
 * @version 0.1
 */
class Settings extends Forms\Form {

    function structure()
    {
        $this -> action = "user/settings";
        
        $i = new Forms\TextBox("password1", self :: t(40));
        $i -> minLength = 5;
        $i -> description = self :: t(501, array($i -> minLength));
        $i -> password = true;
        $i -> disableAutocomplete = true;
        $this -> addItem($i);

        $i = new Forms\TextBox("password2", self :: t(310));
        $i -> minLength = 5;
        $i -> description = self :: t(501, array($i -> minLength));
        $i -> disableAutocomplete = true;
        $i -> password = true;
        $this -> addItem($i);

        $i = new Forms\TextBox("name", self :: t(60));
        $i -> required = true;
        $this -> addItem($i);

        $i = new Forms\TextBox("email", self :: t(50));
        $i -> required = true;
        $i -> format = "email";
        $this -> addItem($i);

        $b = new Forms\Button(self :: t(520), Forms\Button::OK);
        $this -> addButton($b);
    }

    function validate()
    {
        $error = FALSE;

        // both?
        if ($this -> get("password1") XOR $this -> get("password2")) {
            \Cyfy\Message :: set(self :: t(530), \Cyfy\Message :: ERROR);
            $error = true;
        }

        // passwords
        if ($this -> get("password1") != $this -> get("password2")) {
            \Cyfy\Message :: set(self :: t(340), \Cyfy\Message :: ERROR);
            $error = true;
        }
        
        return !$error;
    }

    function submit()
    {
        $query = array("UPDATE [:cyfy:Users-users] SET");
        if ($this -> get("password1"))
        {
            array_push($query, '[password] = %s, ', Module :: hashPassword($this -> get("password1")));
        }

        \dibi :: query($query, '[name] = %s,', $this->get('name'),  'email = %s', $this -> get("email"), ' WHERE uid = %i', Current :: $uid);

        \Cyfy\Message :: set(self :: t(540));
        // relogin if needed
        if ($this -> get("password1")) {
           Current :: login(Current :: $username, $this -> get("password1"));
        }
        return true;
    }

}
    